'use strict';

var qiniu = require("qiniu");

var router = require('express').Router();
var ComFunc = require('../comfunc');
//需要填写你的 Access Key 和 Secret Key
qiniu.conf.ACCESS_KEY = '8m8pzXMjK2BCbh3cxXYurFrV9fHAkxa5nG3p929B';
qiniu.conf.SECRET_KEY = 'AdT1QuHPkI0dhqnOzGCoLmjzh0RwwKFdtQ5_uh3y';

//要上传的空间
var bucket = 'leqin';

var accessKey = '8m8pzXMjK2BCbh3cxXYurFrV9fHAkxa5nG3p929B';
var secretKey = 'AdT1QuHPkI0dhqnOzGCoLmjzh0RwwKFdtQ5_uh3y';
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

var options = {
  scope: bucket,
};

var config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z1;
config.useCdnDomain = true;

//构建上传策略函数，设置回调的url以及需要回调给业务服务器的数据
function uptoken(bucket, key) {
  var putPolicy = new qiniu.rs.PutPolicy(bucket+":"+key);
  // putPolicy.callbackUrl = 'http://your.domain.com/callback';
  putPolicy.callbackBody = 'filename=$(fname)&filesize=$(fsize)';
  // putPolicy.returnBody = 
  return putPolicy.token();
}

//要上传文件的本地路径

function uploadFile(localFile,filename,callback) {
  var key = 'datamax_'+ComFunc.getTimeStamp()+Math.round(new Date() / 1000);
  var putPolicy = new qiniu.rs.PutPolicy(options);
  var uploadToken=putPolicy.uploadToken(mac);
  var resumeUploader = new qiniu.resume_up.ResumeUploader(config);
  var putExtra = new qiniu.resume_up.PutExtra();
  putExtra.progressCallback = function(uploadBytes, totalBytes) {
    console.log("progress:" + uploadBytes + "(" + totalBytes + ")");
  }
  putExtra.params = {
    "filename": filename
  }
  putExtra.fname = filename;
  resumeUploader.putFile(uploadToken, key, localFile, putExtra, function(respErr,
      respBody, respInfo) {
      if (respErr) {
          throw respErr;
      }
      if (respInfo.statusCode == 200) {
        return callback(respBody);
      } else {
        console.log(respInfo.statusCode);
        console.log(respBody);
        return callback(respInfo)
      }
  });
}

module.exports = router;
module.exports.uploadFile = uploadFile;